package WrittenTest;

class ListNode {
    public ListNode next;
    public int val;

    public ListNode(int val) {
        this.val = val;
    }
}

public class test13 {
    public static ListNode head1;
    public static ListNode head2;

    // 翻转
    public static ListNode Flip(ListNode head) {
        if (head == null) {
            return null;
        }
        if (head.next == null) {
            return head;
        }
        // cur存储要反转的节点
        ListNode cur = head.next;
        head.next = null;
        while (cur != null) {
            // curNext来存储第三个节点
            ListNode curNext = cur.next;
            cur.next = head;
            // 更新头结点
            head = cur;
            cur = curNext;
        }
        return head;
    }

    // 两数相加二 (链表)
    public static void main(String[] args) {
        // 将链表进行翻转
        ListNode l1 = Flip(head1);
        ListNode l2 = Flip(head2);
        // pre存储相加的数
        ListNode pre = new ListNode(0);
        ListNode cur = pre;
        // tmp表示进位
        int tmp = 0;
        while (l1 != null || l2 != null || tmp != 0) {
            // 判断两个链表是否为空
            if (l1 != null) {
                tmp += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                tmp += l2.val;
                l2 = l2.next;
            }
            cur.next = new ListNode(tmp % 10);
            cur = cur.next;
            tmp /= 10;
        }
        System.out.println(Flip(pre.next));
    }
}
